package com.freedy.concurrent.Monitors.patterns;

import lombok.extern.slf4j.Slf4j;

/**
 * 同步模式之交替输出
 * 固定顺序
 * 使用 wait notify 实现
 *
 * @author Freedy
 * @date 2021/4/22 22:07
 */
@Slf4j
public class SequenceControlAlternately {
    private static final Object LOCK = new Object();
    private static int turn = 0;

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> print("A", 0), "T1");
        Thread t2 = new Thread(() -> print("B", 1), "T2");
        Thread t3 = new Thread(() -> print("C", 2), "T3");

        t1.start();
        t2.start();
        t3.start();
    }

    private static void print(String str, int turned) {
        for (int k = 0; k < 3; k++) {
            synchronized (LOCK) {
                while (turn % 3 != turned) {
                    try {
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.info(str);
                turn++;
                LOCK.notifyAll();
            }
        }
    }
}
